package api.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class JDKProxyTests {
    public static void main(String[] args) {

        //目标对象
        NoticeService noticeService = new NoticeServiceImpl();
        //基于JDK方式为目标对象创建代理对象
        //2.1获取ClassLoader,类加载器
        ClassLoader classLoader  = noticeService.getClass().getClassLoader();
        //2.2获取目标对象实现的接口
        Class<?>[] interfaces = noticeService.getClass().getInterfaces();
        //2.3创建InvocationHandler(为代理对象处理业务的对象)
        class ProxyHandler implements InvocationHandler{
     //   InvocationHandler handler = new InvocationHandler() {
            private Object targetObj;
            public ProxyHandler(Object targetObj){
                this.targetObj = targetObj;
            }

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //在此方法中如何调用目标对象方法:目标对象,方法,参数
                Object result = method.invoke(targetObj,args);
               // System.out.println(proxy.getClass().getClassLoader());
                  //System.out.println(proxy.getClass().getName());
//                System.out.println(method);
//                Long[] array = (Long[])args[0];
//                System.out.println(array[0]+","+array[1]+","+array[2]);
                return result;
            }
        };
        NoticeService proxy = (NoticeService) Proxy.newProxyInstance(
                classLoader,//类加载器(负责加载底层产生的代理类型)
                interfaces,//代理类要实现的接口(和目标类一样的接口)
                new ProxyHandler(noticeService));//代理类的处理器
        System.out.println(proxy.getClass().getName());
        //调用代理对象的方法,底层会调用handle对象的invoke方法
        proxy.deleteById(10L,20L,30L);
        //Controller-Service接口-Proxy--InvocationHandler--ServiceImpl-Dao
    }
}
